package com.example.lhsama.controller;

import com.example.lhsama.domain.Member;
import com.example.lhsama.domain.Orders;
import com.example.lhsama.domain.Product;
import com.example.lhsama.domain.User;
import com.example.lhsama.service.MemberService;
import com.example.lhsama.service.OrdersService;
import com.example.lhsama.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.jws.WebParam;
import java.util.List;

@Controller
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private MemberService memberService;

    @RequestMapping("/list")
    public String list(Model model){
        List<Orders> ordersList = ordersService.findAll();

        model.addAttribute("orders",ordersList);
        return "/pages/ordersList";
    }

    @RequestMapping("/detail/{id}")
    public String detail(Model model, @PathVariable Integer id){
        Orders orders = ordersService.findById(id);
        int total = 0;
        for (Product product : orders.getProducts()) {
            total+=product.getCount()*product.getPrice();
        }
        model.addAttribute("orders",orders);
        model.addAttribute("total",total);
        return "/pages/ordersDetail";
    }

    @RequestMapping("/close/{id}")
    public String close(@PathVariable Integer id){
        Orders orders = ordersService.findById(id);
        if (orders.getOrderStatus()==1){
            orders.setOrderStatus(0);
            ordersService.updateById(orders);
        }else{
            orders.setDeleted(1);
            ordersService.updateById(orders);
        }

        return "redirect:/orders/list";
    }

    @RequestMapping("/open/{id}")
    public String open(@PathVariable Integer id){
        Orders orders = ordersService.findById(id);
        orders.setOrderStatus(1);
        ordersService.updateById(orders);
        return "redirect:/orders/list";
    }

    @RequestMapping("/recovery/{id}")
    public String recovery(@PathVariable Integer id){
        Orders orders = ordersService.findById(id);
        orders.setDeleted(0);
        ordersService.updateById(orders);
        return "redirect:/orders/list";
    }

}
